import { asyncRoutes, constantRoutes } from '@/router'
import Layout from '@/layout'
import { getInfo } from '@/api/user'
import { walleRouter } from '@/router/modules/walle'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

function getUrl(item) {
  if (item.url) {
    const tmppath = item.url.substr(item.url.indexOf('/', 1))
    return '/walle' + (tmppath === '/' ? '' : tmppath)
  } else {
    return '/walle/' + item.title
  }
}

/**
 * 判断一个字符串是以指定字符串结尾的
 */
function endWith(str, endStr) {
  var d = str.length - endStr.length;
  return (d >= 0 && str.lastIndexOf(endStr) === d);
}

/**
 * Walle菜单Icon特殊转换处理
 */
function doWalleMenuIcon(item) {
  switch(item.icon) {
    case "wl-icon-main": return "wl-icon-main" // 首页
    case "wl-icon-space-set": return "el-icon-star-off" // 空间管理
    case "wl-icon-user-set": return "el-icon-user" // 用户管理
    case "wl-icon-project-set": return "el-icon-shopping-bag-1" // 项目中心
    case "wl-icon-deploy-set": return "el-icon-setting" // 部署管理
    case "leaf":
      if (item.url === "/environment/index") {
        return "el-icon-office-building"
      } else if (item.url === "/server/index") {
        return "el-icon-refrigerator"
      } else if (item.url === "/project/index") {
        return "el-icon-shopping-bag-2"
      }
  }
  return item.icon
}

/**
 * Walle菜单（项目管理、部署管理）特殊处理，适合vue-element-admin的面包屑
 */
function doWalleMenu(menu, item) {
  if (!item.url) {
    menu.redirect = 'noRedirect' // 重定向地址，在面包屑中点击会重定向去的地址; noRedirect 的时候该路由在面包屑导航中不可被点击
  }
  if (item.title === "项目中心") { // 项目中心
    menu.path = "/walle/project"
    menu.name = "WalleProjects"
  } else if (menu.path === "/walle/project/index") { // 项目中心->项目管理 
    menu.name = "WalleProject"
    menu.children.push(
      {
        path: '/walle/project/member',
        name: 'MemberProject',
        component: (resolve) => require([`@/views/walle/project/member.vue`], resolve),
        hidden: true,
        meta: { title: '成员管理', roles: state.roles },
        children: []
      }, 
      {
        path: '/walle/project/create',
        name: 'CreateProject',
        component: (resolve) => require([`@/views/walle/project/editproject.vue`], resolve),
        hidden: true,
        meta: { title: '创建', roles: state.roles },
        children: []
      }, 
      {
        path: '/walle/project/update',
        name: 'UpdateProject',
        component: (resolve) => require([`@/views/walle/project/editproject.vue`], resolve),
        hidden: true,
        meta: { title: '编辑', roles: state.roles },
        children: []
      }, 
      {
        path: '/walle/project/view',
        name: 'ViewProject',
        component: (resolve) => require([`@/views/walle/project/editproject.vue`], resolve),
        hidden: true,
        meta: { title: '查看', roles: state.roles },
        children: []
      }, 
      {
        path: '/walle/project/check',
        name: 'CheckProject',
        component: (resolve) => require([`@/views/walle/project/check.vue`], resolve),
        hidden: true,
        meta: { title: '检测报告', roles: state.roles },
        children: []
      }
    )
  } else if (menu.path === "/walle/deploy") { // 部署管理
    menu.children[0].name = "WalleDeploy"
    menu.children[0].children.push(
      {
        path: '/walle/deploy/create',
        name: 'CreateTask',
        component: (resolve) => require([`@/views/walle/deploy/create.vue`], resolve),
        hidden: true,
        meta: { title: '新建上线单', roles: ['SUPER', 'OWNER', 'MASTER', 'DEVELOPER', 'REPORTER'] },
        children: []
      },
      {
        path: '/walle/deploy/view',
        name: 'ViewTask',
        component: (resolve) => require([`@/views/walle/deploy/view.vue`], resolve),
        hidden: true,
        meta: { title: '查看上线单', roles: ['SUPER', 'OWNER', 'MASTER', 'DEVELOPER', 'REPORTER'] },
        children: []
      }
    )
  }
}

/**
 * 后台查询的菜单数据拼装成路由格式的数据
 * @param routes
 */
export function generaMenu(routes, data, level) {
  level = (level === undefined) ? 1 : level
  data.forEach(item => {
    const path = getUrl(item)
    let menu
    if (item.url !== '/') { // 首页已经默认存在
      if (item.sub_menu && item.sub_menu.length > 0) { // 有下级子菜单
        menu = {
          path: path,
          name: 'menu_' + item.title,
          component: (level === 1) ? Layout : null,
          meta: { title: item.title, icon: doWalleMenuIcon(item), roles: state.roles },
          children: []
        }
        generaMenu(menu.children, item.sub_menu, level + 1)
      } else { // 叶子菜单
        if (level === 1) { // 一级目录
          menu = {
            path: endWith(path, '/index') ? path.substr(0,path.length - 6) : path,
            component: Layout,
            children: [{
                path: 'index',
                name: 'Walle_' + level + "_"+ item.title,
                component: (resolve) => require([`@/views${path}.vue`], resolve),
                meta: { title: item.title, icon: doWalleMenuIcon(item), roles: state.roles },
                children: []
            }]
          }
        } else {
          menu = {
            path: path,
            name: 'menu_' + item.title,
            component: (resolve) => require([`@/views${path}.vue`], resolve),
            meta: { title: item.title, icon: doWalleMenuIcon(item), roles: state.roles },
            children: []
          }
        }
      }
      doWalleMenu(menu, item)
      routes.push(menu)
    }
  })
  return routes
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  if (roles.includes('SUPER')) { // admin
    return routes || []
  }
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  // generateRoutes({ commit }, roles) {
  //   return new Promise(resolve => {
  //     let accessedRoutes
  //     if (roles.includes('admin')) {
  //       accessedRoutes = asyncRoutes || []
  //     } else {
  //       accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
  //     }
  //     commit('SET_ROUTES', accessedRoutes)
  //     resolve(accessedRoutes)
  //   })
  // }
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      // 先查询后台并返回左侧菜单数据并把数据添加到路由
      getInfo(state.token).then(response => {
        if (!response.data || response.data.code !== 0) {
          this.$message({
            message: '菜单数据加载异常',
            type: 0
          })
          return
        }
        // const myroutes = walleRouter // 开发调试时使用的walle2.0菜单静态路由对象
        const myroutes = generaMenu([], response.data.data.menu)
        const accessedRoutes = filterAsyncRoutes(myroutes, roles)
        commit('SET_ROUTES', accessedRoutes)
        resolve(accessedRoutes)
      }).catch(error => {
        console.log(error)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
